/** 菜单处理 **/
import { RouteRecordRaw } from 'vue-router'
/**
 * 过滤菜单
 */
function filterMenu (menus:Array<RouteRecordRaw>, parentPath = '') {
  const result:Array<RouteRecordRaw> = []

  // 排序， 根据 meta 配置的 orderNo 属性
  menus.sort((a, b) => {
    return (a.meta?.orderNo || 0) - (b.meta?.orderNo || 0)
  })

  menus.forEach((item) => {
    const meta = item.meta

    // 添加父级路径， 路径不以 '/' 开始
    if (!isRoot(item.path)) {
      item.path = `${parentPath}/${item.path}`
    }

    const children = item.children

    // 递归
    if (children && children.length > 0) {
      item.children = filterMenu(children, item.path)
    }

    // 仅显示子级， 当路由子菜单有且仅有一个时
    if (!meta?.alwaysShow && children && children.length === 1) {
      item = children[0]
    }

    result.push(item)

    // // 处理需要显示的菜单
    // if (!meta.hidden) {
    // }
  })

  return result
}

// 判断路劲是否以 '/' 开头
const isRoot = (str:string) => /^\//.test(str)

/**
 * 根据路由模块生成菜单
 */
export function generateMenus (routeModules:Array<RouteRecordRaw>) {
  const menus = JSON.parse(JSON.stringify(routeModules))
  return filterMenu(menus, '')
}

/**
 * 生成面包屑导航
 * @param { Array } menuModules 菜单
 * @param { String } currentPath 当前路由
 */
export function generatePaths (menuModules:Array<any>, currentPath:string) {
  const menus = JSON.parse(JSON.stringify(menuModules))
  interface MenuMap {
    [prop: string]: any
  }
  const menuMap:MenuMap = {}
  // 递归获取树形数据 当前值的路径
  const getParentPaths = (treeData:Array<RouteRecordRaw>) => {
    const paths:Array<RouteRecordRaw> = []
    for (let i = 0; i < treeData.length; i++) {
      const item = treeData[i]

      paths.push(item)

      if (item.name) {
        // 构建以 路由 name 属性 的菜单一维对象
        menuMap[item.name] = item
      }

      if (item.path === currentPath) {
        // 匹配到子节点 直接返回结果
        return paths
      }

      if (item.children && item.children.length > 0) {
        const result:Array<RouteRecordRaw> = getParentPaths(item.children)
        if (result) {
          return paths.concat(result)
        }
      }

      // 删除未匹配的节点
      paths.pop()
    }

    return paths
  }

  // 获取路径
  const pathNav = getParentPaths(menus) || []

  // 添加父级激活
  pathNav.forEach((item, i) => {
    if (!item.meta) return

    const activeParent = item.meta.activeParent as string
    const parentMenu = menuMap[activeParent]
    const currentParent = pathNav[i - 1]

    if (typeof activeParent === 'boolean') {
      // 激活当前父级面包屑导航
      currentParent.active = true
    }

    if (parentMenu && parentMenu.path === currentParent.path) {
      // 激活当前父级面包屑导航
      currentParent.active = true
    } else if (parentMenu && currentParent) {
      // 为其新增一个需要激活面包屑导航父级
      parentMenu.active = true
      pathNav.splice(i, 0, parentMenu)
    }
  })

  return pathNav
}
